package org.wuguike.json.sax;

public class JString implements JObject {

	private final String inner_string;

	public JString(String s) {
		inner_string = s;
	}

	public String getString() {
		return inner_string;
	}

	private static String encode(String s) {
		int len = s.length();
		StringBuilder sb = new StringBuilder(len + 2);
		sb.append('"');
		for (int i = 0; i < len; i++) {
			char c = s.charAt(i);
			switch (c) {
			case '\r':
				sb.append("\\r");
				break;
			case '\n':
				sb.append("\\n");
				break;
			case '\t':
				sb.append("\\t");
				break;
			case '\b':
				sb.append("\\b");
				break;
			case '\f':
				sb.append("\\f");
				break;
			case '\\':
				sb.append("\\\\");
				break;
			case '"':
				sb.append("\\\"");
				break;
			default:
				if (c > 128) {
					sb.append(String.format("\\u%04x", (int) c));
				} else {
					sb.append(c);
				}
			}
		}
		sb.append('"');
		return sb.toString();
	}

	@Override
	public String toJson(int indent) {
		return toJson(0, 0);

	}

	@Override
	public String toJson(int deep, int indent) {
		return encode(inner_string);
	}

	@Override
	public boolean equals(JObject o) {
		if (o.getClass() == JString.class) {
			return inner_string.equals(((JString) o).inner_string);
		} else {
			return false;
		}
	}
}
